//
//  AppDelegate+NRWJPush.m
//  NRWMall
//
//  Created by 张记 on 2018/6/20.
//  Copyright © 2018年 com.anpxd. All rights reserved.
//

#import "AppDelegate+NRWJPush.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import "NRWNavigationController.h"
#import "NRWMySubscriptionVC.h"
#import "NRWCarPushMsgModel.h"
#import "NRWMyCollectionVC.h"

@implementation AppDelegate (NRWJPush)

-(void)initJPushWithWithOptions:(NSDictionary *)launchOptions{
    
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:nil];
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccessful:) name:userLoginSuccess object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(signOutSuccessful:) name:userSignOutSuccess object:nil];

            NSLog(@"registrationID获取成功：%@",registrationID);
            
        }else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    if (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]) {
        
        [self jpushDistributionWithDict:launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] isTouchPush:YES];
    }
    
}
-(void)loginSuccessful:(NSNotification *)nofit{
    NSMutableSet *tagSet = [NSMutableSet set];
    NSString *userId = [NRWUserInfoModel shared].userId;
    
    [JPUSHService setTags:tagSet.copy completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
        
    } seq:0];
    
    if (userId.length > 0) {
        
        [JPUSHService setAlias:userId completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            
        } seq:0];
    }

}
-(void)signOutSuccessful:(NSNotification *)nofit{
    
    [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        
    } seq:0];
    
    [JPUSHService cleanTags:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
        
    } seq:0];
}
#pragma mark - publicMethod
- (void)setPushBage:(NSInteger)bage {
    
    [JPUSHService setBadge:bage];
}
- (void)jpushDistributionWithDict:(NSDictionary *)dict isTouchPush:(BOOL)isTouchPush {
    
    NSString *type = dict[@"type"];
    
    if (!isEmptyString(type)) {//如果type有值, 不是系统消息推送
       
    } else {
        [NRWCarPushMsgModel addNewModelWithUserInfo:dict];
  

        if (isTouchPush) {
            
            [self turnToNotificationVC:dict[@"iOSPath"]];
        }
        
    }
}


- (void)turnToNotificationVC:(NSString *)path {
    
    if ([NRWUserInfoModel shared].isLogin == NO) {
        return;
    }
    
    [self needReloadPushMessageVCData:path];
    
}

- (void)needReloadPushMessageVCData:(NSString *)path {
    
    UITabBarController *tabbarVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
	NRWNavigationController *nav = (NRWNavigationController *)tabbarVC.selectedViewController;
    
    if ([path isEqualToString:@"selectTemplate"]) {
        
        //如果当前页面就是 通知vc, 直接刷新数据
        if ([[AppDelegate shareAppDelegate].getCurrentUIVC isKindOfClass:NSClassFromString(@"NRWMySubscriptionVC")]) {
            
            UIViewController *vc = [AppDelegate shareAppDelegate].getCurrentUIVC;
            
            [vc performSelector:@selector(reloadData)];
            
            return;
        }
        
        //如果当前视图堆栈里面有 通知vc  直接跳回去并刷新数据
        for (UIViewController *vc in nav.viewControllers) {
            
            if ([vc isKindOfClass:NSClassFromString(@"NRWMySubscriptionVC")]) {
                
                [nav popToViewController:vc animated:YES];
                
                [vc performSelector:@selector(reloadData)];
                
                return;
            }
        }
        //如果都没有   创建一个跳过去
        [nav pushViewController:[NRWMySubscriptionVC new] animated:YES];
    }else{
   
        //如果当前页面就是 通知vc, 直接刷新数据
        if ([[AppDelegate shareAppDelegate].getCurrentUIVC isKindOfClass:NSClassFromString(@"NRWMyCollectionVC")]) {
            
            UIViewController *vc = [AppDelegate shareAppDelegate].getCurrentUIVC;
            
            [vc performSelector:@selector(reloadData)];
            
            return;
        }
        
        //如果当前视图堆栈里面有 通知vc  直接跳回去并刷新数据
        for (UIViewController *vc in nav.viewControllers) {
            
            if ([vc isKindOfClass:NSClassFromString(@"NRWMyCollectionVC")]) {
                
                [nav popToViewController:vc animated:YES];
                
                [vc performSelector:@selector(reloadData)];
                
                return;
            }
        }
        //如果都没有   创建一个跳过去
        [nav pushViewController:[NRWMyCollectionVC new] animated:YES];
    }
    
 
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark- JPUSHRegisterDelegate
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler  API_AVAILABLE(ios(10.0)){
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
        [self jpushDistributionWithDict:userInfo isTouchPush:NO];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
        [self jpushDistributionWithDict:userInfo isTouchPush:YES];
    }
    completionHandler();  // 系统要求执行这个方法
}

#endif
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    
    if (application.applicationState == UIApplicationStateActive) {//在前台
        
        NRWNavigationController *nav = (NRWNavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        
        if ([nav.topViewController isKindOfClass:NSClassFromString(@"NRWCarNotificationVC")]) {
            
            UIViewController *vc = nav.topViewController;
            
            [vc performSelector:@selector(reloadData)];
        }
    }
    
    completionHandler(UIBackgroundFetchResultNewData);
}

@end
